<?php
/**
 * @author Feng
 * @date 2012-6-17
 */
class collection_special_concept extends system_concept_abstract {
	
	public function init() {
		$this->setRowClass('collection_special_row');
		$this->setModel('collection_special_model', 'special');
		$this->setJoinModel('collection_item_model', 'item.id = special.item_id', 'item');
		$this->setJoinModel('resource_link_model', 'link.key = special.link', 'link');
		$this->setJoinModel('collection_site_model', 'item.site_id = site.id', 'site');
		$this->setJoinLeftModel('collection_rule_model', 'rule.id = special.rule_id', 'rule');
		$this->setModelCols('special', array('id', 'link', 'item_id', 'title', 'cover', 'rule_id', 'params', 'creationtime'));
		$this->setModelCols('item', array('site_id'));
		$this->setModelCols('site', array('lang', 'name', 'cover', 'charset', 'description', 'is_active'));
		$this->setModelCols('link', array('key', 'url'));
		$this->setModelCols('rule', array('type', 'rule'));
	}
	
	public function save(collection_special_row $row) {
		$row->set('item_id', $row->get('item_id'));
		if(!$row->getItemId()) {
			throw new collection_exception("ITEM ID can not be Empty.");
		}
		if(!$row->getTitle()) {
			throw new collection_exception("SPECIAL Title can not be Empty.");
		}
		if(!$row->getUrl()) {
			throw new collection_exception("SPECIAL URL can not be Empty.");
		}
		if(!$row->get('params')) {
			$row->setParams(array());
		}
		$key = system_encrypt::shortUrl($row->getUrl());
		$row->setLink($key);
		$row->setKey($key);
		if(!$row->getRuleId() || ($row->getRuleId() && !$this->getModel('rule')->fetchRow(array('id = ?' => $row->getRuleId())))) {
			$type = new collection_rule_type('special');
			$row->setType($type->getId());
			$rid = $this->getModel('rule')->insert($row->getModelData('rule'));
			$row->setRuleId($rid);
		} else {
			$this->getModel('rule')->update($row->getModelData('rule'), array('id = ?' => $row->getRuleId()));
		}
		if($row->getId()) {
			if($this->getModel('special')->fetchRow(array('id != ?' => $row->getId(), 'link = ?' => $key))) {
				throw new collection_exception("SPECIAL is already Existing.");
			}
			$this->getModel('special')->update($row->getModelData('special'), array('id = ?' => $row->getId()));
		} else {
			if($this->getModel('special')->fetchRow(array('link = ?' => $key))) {
				throw new collection_exception("SPECIAL is already Existing.");
			}
			$row->setCreationtime(system_date::timestamp());
			$id = $this->getModel('special')->insert($row->getModelData('special'));
			$row->setId($id);
		}
		if(!$this->getModel('link')->fetchRow(array('`key` = ?' => $key))) {
			$this->getModel('link')->insert($row->getModelData('link'));
		}
		return $row;
	}
	
	public function delete($row) {
		return ;
	}

}
